package com.zh.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zh.common.ErrorCode;
import com.zh.domain.Model.ws.SimpleAttacheModel;
import com.zh.domain.Model.ws.SimpleUserModel;
import com.zh.domain.dto.task.AddTaskCommentRequest;
import com.zh.domain.dto.task.PageTaskCommentRequest;
import com.zh.domain.entity.Message;
import com.zh.domain.entity.TaskComments;
import com.zh.domain.vo.task.TaskCommentVo;
import com.zh.domain.vo.task.TaskVo;
import com.zh.domain.vo.user.UserVO;
import com.zh.exception.ThrowUtils;
import com.zh.job.TaskManager;
import com.zh.service.MessageService;
import com.zh.service.TaskCommentsService;
import com.zh.mapper.TaskCommentsMapper;
import com.zh.service.TaskService;
import com.zh.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Administrator
 * @description 针对表【task_comments(任务评论表)】的数据库操作Service实现
 * @createDate 2025-02-09 16:24:10
 */
@Service
public class TaskCommentsServiceImpl extends ServiceImpl<TaskCommentsMapper, TaskComments>
        implements TaskCommentsService {

    @Resource
    private TaskCommentsMapper taskCommentsMapper;
    @Resource
    private UserService userService;
    @Resource
    private MessageService messageService;
    @Resource
    private TaskService taskService;
    private static final String attacheKey = "A";
    private static final String atUserKey = "M";

    @Override
    @Transactional
    public Boolean addTaskComment(AddTaskCommentRequest addTaskCommentRequest) {
        int loginId = StpUtil.getLoginIdAsInt();
        // 参数校验
        Integer taskId = addTaskCommentRequest.getTaskId();
        Integer sendId = addTaskCommentRequest.getSendId();
        String content = addTaskCommentRequest.getContent();
        List<SimpleAttacheModel> attacheList = addTaskCommentRequest.getAttacheList();
        List<Integer> atUserList = addTaskCommentRequest.getAtUserList();
        ThrowUtils.throwIf(taskId == null, ErrorCode.PARAMS_ERROR, "任务id不能为空");
        if (sendId == null) {
            sendId = loginId;
        }
        //2.拼装 附件、@人信息
        Map<String, Object> params = new HashMap<>();

        if (attacheList != null) {
            params.put(attacheKey, JSONUtil.toJsonStr(attacheList));
        }
        if (atUserList != null) {
            List<UserVO> userVOList = userService.listUserVoByIds(atUserList);
            List<SimpleUserModel> simpleUserModelList = userVOList.stream().map(userVO -> {
                SimpleUserModel simpleUserModel = new SimpleUserModel();
                simpleUserModel.setId(userVO.getId());
                simpleUserModel.setName(userVO.getName());
                simpleUserModel.setAvatar(userVO.getAvatar());
                return simpleUserModel;
            }).collect(Collectors.toList());
            params.put(atUserKey, JSONUtil.toJsonStr(simpleUserModelList));
        }
        //3.插入数据库
        TaskComments taskComments = BeanUtil.copyProperties(addTaskCommentRequest, TaskComments.class);
        taskComments.setSendId(sendId);
        taskComments.setParams(params);
        taskComments.setCreateAt(LocalDateTime.now());
        taskComments.setCreateBy(loginId);
        taskComments.setUpdateAt(LocalDateTime.now());
        taskComments.setUpdateBy(loginId);
        taskComments.setStatus(1);
        taskComments.setDeleted(0);
        boolean success = taskCommentsMapper.insert(taskComments) > 0;
        //4.发送消息给被@人
        TaskManager.execute(() -> sendMessageWhenAdd(loginId, taskComments, atUserList));
        return success;
    }

    public void sendMessageWhenAdd(Integer sendId, TaskComments taskComments, List<Integer> revciverList) {
        Message message = new Message();
        message.setSendId(sendId);
        message.setContent(taskComments.getContent());
        message.setCreateBy(sendId);
        message.setUpdateBy(sendId);
        message.setCreateAt(LocalDateTime.now());
        message.setUpdateAt(LocalDateTime.now());
        message.setNoticeType(1);
        message.setType(3);
        TaskVo taskVo = taskService.getDetail(taskComments.getTaskId());
        message.setParams(Map.of(
                "taskId", taskComments.getTaskId().toString(),
                "payloadType", "task",
                "title", taskVo.getTitle()
        ));
        messageService.sendMessage(message, revciverList);
    }

    @Override
    public Page<TaskCommentVo> pageTaskComment(PageTaskCommentRequest pageTaskCommentRequest) {
        Integer taskId = pageTaskCommentRequest.getTaskId();
        ThrowUtils.throwIf(null == taskId, ErrorCode.PARAMS_ERROR, "任务Id不能为空");
        pageTaskCommentRequest.standardizeSize();
        Integer current = pageTaskCommentRequest.getCurrent();
        Integer pageSize = pageTaskCommentRequest.getPageSize();
        Page<TaskComments> page = new Page<>(current, pageSize);
        LambdaQueryWrapper<TaskComments> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TaskComments::getTaskId, taskId)
                .orderByDesc(TaskComments::getCreateAt)
                .orderByDesc(TaskComments::getId)
        ;
        Page<TaskComments> taskCommentsPage = taskCommentsMapper.selectPage(page, queryWrapper);
        List<TaskComments> records = taskCommentsPage.getRecords();
        // 获取评论人信息
        List<Integer> userIdList = records
                .stream()
                .map(TaskComments::getSendId)
                .collect(Collectors.toList());
        List<UserVO> userVOList = userService.listUserVoByIds(userIdList);
        Map<Integer, UserVO> userVOMap = userVOList.stream().collect(Collectors.toMap(UserVO::getId, userVO -> userVO));
        List<TaskCommentVo> resultList = new ArrayList<>();
        records.forEach(taskComments -> {
            TaskCommentVo taskCommentVo = BeanUtil.copyProperties(taskComments, TaskCommentVo.class);
            UserVO userVO = userVOMap.get(taskComments.getSendId());
            taskCommentVo.setSendUser(userVO);
            resultList.add(taskCommentVo);
        });
        Page<TaskCommentVo> pageResult = new Page<>(current, pageSize);
        BeanUtil.copyProperties(taskCommentsPage, pageResult);
        pageResult.setRecords(resultList);
        return pageResult;
    }
}




